package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.FaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.log4j.Log4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.joda.time.DateTime;
import org.joda.time.Years;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
@Log4j
public class UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FaceTemplate faceTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;



    /**
     * 完善个人信息功能
     * @param userInfoVo
     */
    public void loginReginfo(UserInfoVo userInfoVo) {

//        String tokenKey = "TOKEN_" + token;
//        // 根据key查询redis是否登录，没有值则登录超时
//        String userStr = redisTemplate.opsForValue().get(tokenKey);
//        if(StringUtils.isEmpty(userStr)){
//            throw new TanHuaException(ErrorResult.loginFail());
//        }
//
//        // 有值，调用服务提供者保存用户信息
//        User user = JSON.parseObject(userStr, User.class);

        //2. 添加个人信息,保存tb_user_info userInfoApi
        //2.1 把userInfoVo转成实体类userInfo
        UserInfo userInfo = new UserInfo();
        //p1: 要复制的源
        //p2: 复制到的目标
        BeanUtils.copyProperties(userInfoVo,userInfo);

        //2.2 设置登录的id
//        userInfo.setId(user.getId());
        userInfo.setId(UserHolder.getUserId());

        // 设置年龄
        userInfo.setAge(getAge(userInfoVo.getBirthday()));

        //2.3 调用api保存用户信息
        userInfoApi.add(userInfo);
    }

    /**
     * 通过年-月-日获取年龄
     * @param yearMonthDay
     * @return
     */
    private int getAge(String yearMonthDay){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date birthDay = sdf.parse(yearMonthDay);
            Years years = Years.yearsBetween(new DateTime(birthDay), DateTime.now());
            return years.getYears();
        } catch (ParseException e) {
            log.error("获取用户年龄失败!", e);
            return 0;
        }
    }

    /**
     * 完善个人信息-上传头像
     * @param headPhoto
     */
    public void uploadAvatar(MultipartFile headPhoto) {
        try {
            // 1.根据key查询redis是否登录，没有值，登录超时，请重新登录
//            String tokenKey = "TOKEN_" + token;
//            String userStr = redisTemplate.opsForValue().get(tokenKey);
//
//            User user = JSON.parseObject(userStr, User.class);
//
//            if(StringUtils.isEmpty(userStr)){
//                throw new TanHuaException(ErrorResult.loginFail());
//            }

            // 2.有值，调用百度人脸检测，非人脸，则图片非人像，请重新上传
            if(!faceTemplate.detect(headPhoto.getBytes())){
                throw new TanHuaException(ErrorResult.faceError());
            }

            // 3.是人脸，调用阿里云oss保存头像，失败，则上传头像失败
            // 通过，则要上传到oss存储,得到头像的地址
            String avatarUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

            //5. 构建pojo，更新
            UserInfo userInfo = new UserInfo();
            userInfo.setAvatar(avatarUrl);
//            userInfo.setId(user.getId());
            userInfo.setId(UserHolder.getUserId());

            // 成功，则调用服务更新头像
            userInfoApi.upload(userInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询用户信息
     * @param userID
     * @return
     */
    public UserInfoVo getUserInfo(Long userID) {

        // 1. 获取登录用户id,校验token是否有效
        Long userId = UserHolder.getUserId();

        if(userID != null){
            userId = userID;
        }

        UserInfo userInfo = userInfoApi.findById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();

        if(userInfo != null){
            BeanUtils.copyProperties(userInfo,userInfoVo);
        }

        userInfoVo.setAge(userInfo.getAge().toString());

        return userInfoVo;
    }

    /**
     * 用户资料 - 保存
     * @param userInfoVo
     */
    public void updateUserInfo(UserInfoVo userInfoVo) {
        // 获取用户的id
        Long userId = UserHolder.getUserId();

        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoVo,userInfo);

        userInfo.setAge(getAge(userInfoVo.getBirthday()));
        userInfo.setId(userId);

        userInfoApi.updateUserInfo(userInfo);
    }

    /**
     * 用户资料 - 更新头像
     * @param headPhoto
     * @return
     */
    public void updatePhoto(MultipartFile headPhoto) {

        try {

            // 调用百度人脸检测，非人脸，则图片非人像，请重新上传
            if(!faceTemplate.detect(headPhoto.getBytes())){
                throw new TanHuaException(ErrorResult.faceError());
            }

            // 上传到oss存储
            String originalFilename = headPhoto.getOriginalFilename();
            String uploadStr = ossTemplate.upload(originalFilename, headPhoto.getInputStream());

            // 修改数据库中的图片地址
            // 构建UserInfo对象，设置值
            UserInfo userInfo1 = userInfoApi.findById(UserHolder.getUserId());
            String oldAvatar = userInfo1.getAvatar();

            UserInfo userInfo = new UserInfo();
            userInfo.setAvatar(uploadStr);
            userInfo.setId(UserHolder.getUserId());

            // 更新数据
            userInfoApi.upload(userInfo);

            // 删除云存储中的文件
            ossTemplate.delete(oldAvatar);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
